﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Timers;
using ForfiterAmp.WinClient.WinAmpService;

namespace ForfiterAmp.WinClient
{
    public class PlayerStateListener
    {
        private Timer _timer;
        private const double STATE_UPDATE_INTERVAL = 500;

        /// <summary>
        /// Gets or sets the state of the current player.
        /// </summary>
        /// <value>The state of the current player.</value>
        public PlayerState CurrentPlayerState { get; private set; }

        /// <summary>
        /// Initializes a new instance of the <see cref="PlayerStateListener"/> class.
        /// </summary>
        public PlayerStateListener()
        {
            _timer = new Timer(STATE_UPDATE_INTERVAL);
            _timer.Elapsed += Timer_Elapsed;
        }

        /// <summary>
        /// Occurs when current player state has been changed.
        /// </summary>
        public event EventHandler PlayerStateChanged;

        /// <summary>
        /// Occurs when there are problems with server.
        /// </summary>
        public event UnhandledExceptionEventHandler ServiceErrorOccured;

        /// <summary>
        /// Starts the listener work.
        /// </summary>
        public void Start()
        {
            _timer.Start();
        }

        /// <summary>
        /// Stops the listener work.
        /// </summary>
        public void Stop()
        {
            _timer.Stop();
        }

        private void Timer_Elapsed(object sender, EventArgs e)
        {
            try
            {
                CurrentPlayerState = MainForm.WinAmpServiceClient.GetPlayerState();
                if (PlayerStateChanged != null)
                {
                    PlayerStateChanged(this, EventArgs.Empty);
                }
            }
            catch (Exception ex)
            {
                if (ServiceErrorOccured != null)
                {
                    ServiceErrorOccured(this, new UnhandledExceptionEventArgs(ex, false));
                }
            }
        }
    }
}
